/*
  axios
*/

import axios from 'axios'
import config from '@/config'
import { ElMessage } from 'element-plus'
import router from '@/router'
import storage from './storage'

const service = axios.create({
  baseURL: config.baseApi,
  timeout: 8000,
})

service.interceptors.request.use(req => {
  // TODO
  const headers = req.headers;
  const { token = "" } = storage.getItem('userInfo') || {};
  if (!headers.Authorization) headers.Authorization = 'Bearer ' + token;
  return req;
})

const tokenInvalid = `Token 认证失败, 请重新登录`;
const requestOtherInvalid = '网络连接失败, 请稍后重试'

service.interceptors.response.use(res => {
  const { code, data, msg } = res.data;
  if (code === 200 || code === 0) {
    return data
  } else if (code === 50001) {
    ElMessage.error(tokenInvalid);
    setTimeout(() => {
      router.redirect('/login')
    }, 15000)
    return Promise.reject(tokenInvalid)
  } else {
    ElMessage.error(msg || requestOtherInvalid);
    return Promise.reject(msg)
  }
})

/*
  请求核心函数
*/
function request(options) {
  options.method = options.method || 'GET'
  if (options.method.toLowerCase() === 'get') {
    options.params = options.data
  }
  service.defaults.baseURL = import.meta.env.VITE_BASE_URL
  return service(options)
}

['get', 'post', 'put', 'delete', 'patch'].forEach(item => {
  request[item] = (url, data, options) => {
    return request({
      ...options,
      method: item,
      url,
      data,
    })
  }
})

export default request;
